<template>
  <div>

    <van-toast id="van-toast" />

    <van-popup :show="show_guopin"  position="bottom" :overlay="true">
      <van-picker show-toolbar title="果品和规格" :columns="columns" @change="onChange"   @cancel="Close_cancelGuoPin" @confirm="Close_confirmGuoPin" />
    </van-popup>



    <van-cell-group>
      <van-cell v-if="isEdit" title="订单号" :value="val_.num" />

      <van-cell v-if="isEdit" title="状态" :value="val_.state==1?'已发货':'未发货'" />



      <van-field
        label="果品和规格"
        placeholder="果品和规格"
        @click="Open_GuoPin"
        :value="guopinguige"
        required
        readonly
      />




      <van-cell center title="数量">
        <van-stepper :value="val_.sum" @change="onChangeSum" />
      </van-cell>





        <van-field
          @change="changeVal_site"
          :value="val_.site"
          label="快递地址"
          type="textarea"
          placeholder="请输入快递地址"
          input-class="textarea"
          autosize
          required
        />

      <div class="btnm" v-if="isEdit">
        <van-button type="info" @click="goform(0)" block>提交修改</van-button>
      </div>
      <div class="btnm" v-if="!isEdit">
        <van-button type="info" @click="goform(1)" block>提交新订单</van-button>
      </div>
      <!--<div class="btnm" v-if="!isEdit">-->
        <!--<van-button plain type="info" @click="addguo" block>提交并拷贝</van-button>-->
      <!--</div>-->
    </van-cell-group>
    <van-dialog id="van-dialog" />

  </div>
</template>

<script>
  import Dialog from '../../../static/vant/dialog/dialog';
  import Toast from  '../../../static/vant/toast/toast';
  import * as dayjs from 'dayjs'
  import 'dayjs/locale/zh-cn' // import locale

  import {orderAdd,orderEdit,orderiInfo,categoryList} from '../../api/basisMG'


  export default {
  data () {
    return{
      pickerData:[],
      guopinguige:"",
      columns:[],
      username:"",
      show_guopin:false,
      isEdit:false,
      val_:{
        addtime: "",
        deltime: "",
        guige: "",
        guopin: "",
        num: "",
        site: "",
        state: "",
        sum: 1,
        username: "",
        _id: "",
        _openid: "",
      }
    }
  },

  onShow() {
    this.guopinguige = ""
  },
  //
  // beforeMount(){
  //   },


  mounted() {



    //加载果品目录
    categoryList().then(res => {

          if(res.data.length){
            this.columns = [{
              values: ["请选择果品"],
              className: 'column1'
            },{
              values: ["请选择规格"],
              className: 'column2',
              defaultIndex: 0
            }]


            this.pickerData = res.data;
            console.log(this.pickerData)

            //给一级目录数据
            for(let i = 0;i<res.data.length;i++){
              this.columns[0].values.push({text:res.data[i].text,id:res.data[i].id})
            }


          }
        }
      )



    //可选目录
    //this.columns_guopin = this.globalData.guopinArray
    //this.columns_guige = this.globalData.guigeArray
    this.username = wx.getStorageSync('loginInfo').username

    //判断是新增还是修改
    if(this.$root.$mp.query.id){
      this.isEdit =true
      wx.setNavigationBarTitle({
        title: '修改订单'
      })
      this.loadOrderData()
    }else{
      this.isEdit = false
      //清空原来的表单
      this.val_={
          addtime: "",
          deltime: "",
          guige: "",
          guopin: "",
          num: "",
          site: "",
          state: "",
          sum: 1,
          _id:""
          //username: "",
          //_id: "",
          //_openid: "",
      }
      this.columns_guopin_text = ""
      this.columns_guige_text = ""
    }
  },
  methods: {


    onChange(picker,value,index){
      //if(index == 0){
        var arr = []
        for(var i in this.pickerData){
          if(picker.mp.detail.value[0].id == this.pickerData[i].id){

            var obj = {
              text:"请选择规格"
            }
            arr.push(obj)

            for(var x in this.pickerData[i].children){
              var obj = {
                text:this.pickerData[i].children[x].text,
                id:this.pickerData[i].children[x].id
              }
              if(this.pickerData[i].children[x].show){
                arr.push(obj)
              }
            }


          }
        }
        this.columns[1].values =arr

      try {
        this.guopinguige = (picker.mp.detail.value[0].text||'请选择果品')+" "+ (picker.mp.detail.value[1].text||'请选择规格')

      } catch(err){
        this.guopinguige = picker.mp.detail.value[0].text||'请选择果品'
      }


    },


    loadOrderData(){
      Toast.loading({
        message: '加载中...'
      });

      orderiInfo({"_id":this.$root.$mp.query.id}).then(res => {
       if(res.data){
         let data = res.data
         this.val_ = data


         let guopintextar = this.pickerData.filter((obj,index)=>{
           if(obj.id ==this.val_.guopin){
             return obj
           }
         })

         let guopintextar_text = guopintextar[0].text
         let guigetextar_text = guopintextar[0].children.filter((obj,index)=>{
           if(obj.id ==this.val_.guige){
             return obj
           }
         })[0].text

         this.guopinguige = guopintextar_text + guigetextar_text
         //this.val_.guopin+this.val_.guige
       }
      })
    },

    Open_GuoPin(){
      this.show_guopin = true
    },

    Close_confirmGuoPin(picker) {
      try {
        this.val_.guopin = picker.mp.detail.value[0].id
        this.val_.guige = picker.mp.detail.value[1].id
      }catch (e) {
        this.val_.guige = ""
        this.val_.guopin = ""
      }

      this.show_guopin = false
    },

    Close_cancelGuoPin(){
      this.guopinguige = ""
      this.val_.guopin = ""
      this.val_.guige = ""
      this.show_guopin = false
    },


    onChangeSum(data){
      this.val_.sum = data.mp.detail
    },



    changeVal_site(data){
      this.val_.site = data.mp.detail
    },

    goform(isNew){


      let t = this
      console.log(t.val_)

      if(!t.val_.guopin){
        Dialog.alert({
          message: '没有选择果品，请选择果品'
        })
        return false
      }

      if(!t.val_.guige){
        Dialog.alert({
          message: '没有选择规格，请选择规格'
        })
        return false
      }

      if(!t.val_.site){
        Dialog.alert({
          message: '地址未填写'
        })
        return false
      }

      if(t.val_.site.indexOf(",") != -1){
        t.val_.site = t.val_.site.replace(/,/g,"，")
      }

      if(t.val_.site.indexOf("\n") != -1){
        t.val_.site = t.val_.site.replace(/\n/g," ")
      }



      let neworder = {
        guopin:t.val_.guopin,
        sum:t.val_.sum,
        guige:t.val_.guige,
        site:t.val_.site
      }
      if(isNew){
        neworder.username = t.username
        orderAdd(neworder).then(res => {
          Dialog.alert({
            message: '添加订单成功！'
          }).then(() => {
            wx.redirectTo({
              url: "/pages/order/main"
            })
          });
        })
      }else{
        var timestamp = Date.parse(new Date());
        neworder.edittime = timestamp/1000
        neworder._id = this.val_._id
        orderEdit(neworder).then(res => {
          Dialog.alert({
            message: '修改订单成功！'
          }).then(() => {
            wx.redirectTo({
              url: "/pages/order/main"
            })
          });
        })
      }





    },





  },

  created () {
    // let app = getApp()
  }
}
</script>

<style >
  .btnm{padding: 32rpx}

  .textarea{
    min-height: 222rpx!important;
    padding-top: 20rpx!important;
  }

  page {
    background-color: #fff;
  }



  .tr {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  .th, .td {
    padding: 10px;
    border-bottom: 1px solid #dadada;
    border-right: 1px solid #dadada;
    text-align: center;
    width: 100%;
  }

  .th {
    font-weight: 400;
    background-color: #dadada;
  }

</style>
